package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ChuMingYu
 */
@RestController
@Slf4j
@Api(tags = "套餐相关接口")
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
   private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;


    /**
     * 新增套餐
     * @param
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @ApiOperation(value = "新增套餐接口")
    @PostMapping
    public R addSetmeal(@RequestBody SetmealDto setmealDto){
        setmealService.addSetmealDish(setmealDto);
        return R.success("保存套餐成功");
    }

    /**
     * 分页查询套餐
     * @param
     * @return
     */
    @ApiOperation(value = "套餐分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页记录数",required = true),
            @ApiImplicitParam(name = "name",value = "套餐名称",required = false)
    })
    @GetMapping("/page")
    public R selectSetmealByPage(Integer page,Integer pageSize,String name){
        //分页构造器对象
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        Page<SetmealDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据name进行like模糊查询
        queryWrapper.like(name != null,Setmeal::getName,name);
        //添加排序条件，根据更新时间降序排列
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        setmealService.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<Setmeal> records = pageInfo.getRecords();

        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            //对象拷贝
            BeanUtils.copyProperties(item,setmealDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据分类id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                //分类名称
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    /**
     * 删除套餐
     * @param
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @ApiOperation(value = "删除套餐接口")
    @DeleteMapping
    public  R deleteSetmeal(@RequestParam List<Long> ids){
        //1、判断当前要删除的套餐是否处于售卖状态，如果是，不允许删除
        // select count(*) from setmeal where id in (1,2,3) and status = 1
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getStatus,1);
        setmealLambdaQueryWrapper.in(Setmeal::getId,ids);
        int count = setmealService.count(setmealLambdaQueryWrapper);
        if(count>0){
           throw new CustomException("要删除的套餐处于售卖状态,不允许删除");
        }

        //2、删除套餐：   逻辑删除
        setmealService.removeByIds(ids);

        //3、删除套餐对应的菜品数据：  物理删除
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(qw);
        return R.success("套餐删除成功");
    }

    /**
     * 起售/停售套餐
     * @param
     * @return
     */
    @ApiOperation(value = "起售/停售套餐接口")
    @PostMapping("/status/{status}")
    public R updateSetmealStatus(@PathVariable Integer status,@RequestParam List<Long> ids){
        LambdaUpdateWrapper<Setmeal> uw = new LambdaUpdateWrapper<>();
        uw.set(Setmeal::getStatus,status);
        uw.in(Setmeal::getId,ids);
        setmealService.update(uw);
        return R.success("操作成功");
    }

    /**
     * 根据套餐id查询套餐数据
     * @param
     * @return
     */

    @GetMapping("/{id}")
    public R selectSetmealById(@PathVariable Long id){
        //1、根据套餐id查询套餐数据 select * from setmeal where id =?
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getId,id);
        Setmeal setmeal = setmealService.getOne(setmealLambdaQueryWrapper);

        //2、根据套餐id查询套餐对应的菜品数据 select * from setmeal_dish where setmeal_id = ?
        Long setmealId = setmeal.getId();
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.eq(SetmealDish::getSetmealId,setmealId);
        List<SetmealDish> list = setmealDishService.list(setmealDishLambdaQueryWrapper);

        //3、将套餐 setmeal 和套餐菜品集合 setmealDishList 数据封装到 SetmealDto并返回
        // 3.0 首先new一个SetmealDto对象
        SetmealDto setmealDto = new SetmealDto();
        // 3.1、BeanUtils.copyProperties() 拷贝setmeal到setmealDto中
        BeanUtils.copyProperties(setmeal,setmealDto);
        // 3.2、将setmealDishList 设置到 setmealDto中
        setmealDto.setSetmealDishes(list);
        //4、返回 setmealDto
        return R.success(setmealDto);
    }

    /**
     * 修改套餐
     * @param
     * @return
     */
    @PutMapping
    public R updateSetmeal(@RequestBody SetmealDto setmealDto){
        setmealService.updateSetmealService(setmealDto);
        return R.success("修改套餐成功");
    }


    /**
     * 根据套餐分类id查询该套餐分类下的套餐
     * @author ChuMingYu
     */
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId+'_'+#setmeal.status")
    @ApiOperation(value = "套餐条件查询接口")
    @GetMapping("/list")
    public R getDishByCategoryId(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        qw.eq(setmeal.getStatus() != null ,Setmeal::getStatus,setmeal.getStatus());
        List<Setmeal> list = setmealService.list(qw);
        return R.success(list);
    }
}
